package org.gangcai.mac.shop.activity;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.sina.weibo.sdk.utils.LogUtil;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yuyh.library.imgsel.ImgSelActivity;

import org.gangcai.mac.shop.fragment.CategoryFragment;
import org.gangcai.mac.shop.fragment.CategoryViewFragment;
import org.gangcai.mac.shop.fragment.DataBindingUseFragment;
import org.gangcai.mac.shop.fragment.DynamicFragment;
import org.gangcai.mac.shop.fragment.OrderFragment;
import org.gangcai.mac.shop.fragment.PublicPostFragment;
import org.gangcai.mac.shop.fragment.SPReplayFragment;
import org.gangcai.mac.shop.fragment.SPWebCartFragment;
import org.gangcai.mac.shop.implement.MainTabItemListener;
import org.gangcai.mac.shop.service.BaseAccessibilityService;
import org.gangcai.mac.shop.util.ToastUitl;
import org.json.JSONArray;
import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.Person;
import org.gangcai.mac.shop.common.BaseActivity;
import org.gangcai.mac.shop.common.BaseApplication;
import org.gangcai.mac.shop.fragment.BillFragment;
import org.gangcai.mac.shop.fragment.HomeFragment;
import org.gangcai.mac.shop.fragment.QuotaFragment;
import org.gangcai.mac.shop.fragment.ShopFragment;
import org.gangcai.mac.shop.fragment.UserFragment;
import org.gangcai.mac.shop.manager.RetrofitManager;
import org.gangcai.mac.shop.utils.ContactsUtils;
import org.gangcai.mac.shop.utils.LocationUtils;
import org.gangcai.mac.shop.utils.MatisseUtils;
import org.gangcai.mac.shop.views.SpecialTab;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.hugeterry.updatefun.UpdateFunGO;
import cn.hugeterry.updatefun.config.UpdateKey;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;

public class MainActivity extends BaseActivity implements MainTabItemListener {

    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    private final static int REQUESTCODE = 1; // 返回的结果码
    private int REQUEST_CODE=120;
    @BindView(R.id.tab)
    PageNavigationView tab;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    SparseArray<Fragment> fragments = new SparseArray<>( 5 );

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private static final String LOG_TAG = "ImageDownloader";

    public static boolean isForeground = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        BaseAccessibilityService.getInstance().init( this );
        String uid = SPUtils.getInstance().getString( "uid" );
        setContentView( R.layout.activity_main );
        UpdateKey.API_TOKEN = "ad90d5c3fd0d206b411b8c93e3a21979";
        UpdateKey.APP_ID = "5ce7d4a7548b7a2daffa3908";
//下载方式:
//UpdateKey.DialogOrNotification=UpdateKey.WITH_DIALOG;通过 Dialog 来进行下载
//UpdateKey.DialogOrNotification=UpdateKey.WITH_NOTIFITION;通过通知栏来进行下载(默认)
        UpdateFunGO.init(this);
        ButterKnife.bind( this );
        setSwipeBackEnable( false );
        initView();
        if (hasSdcard()) {
            String pathName = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG;
            File file = new File( pathName );
            if (!file.isDirectory()) {
                file.mkdir();
            }
        } else {
            Toast.makeText( this, "您的手机可能缺少储存卡", Toast.LENGTH_SHORT )
                    .show();
        }
        requestPerssion();
//        if (!isStartAccessibilityService( this, "BaseAccessibilityService" )) {
//            BaseAccessibilityService.getInstance().goAccess();
//        }
        registerMessageReceiver();  // used for receive msg
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority( IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!TextUtils.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    ToastUitl.showShort(showMsg.toString());
                }
            } catch (Exception e){
            }
        }
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        UpdateFunGO.onResume(this);
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        UpdateFunGO.onStop(this);
    }

    public boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals( Environment.MEDIA_MOUNTED )) {
            return true;
        } else {
            return true;
        }
    }

    private void requestPerssion() {

        AndPermission.with( this )
                .permission( Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION,
                        Permission.READ_CONTACTS,
                        Permission.CAMERA )
                .onGranted( new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        // TODO what to do.
                        File externalStorageDirectory = Environment.getExternalStorageDirectory();
                        File mj = new File( externalStorageDirectory.getAbsolutePath(), "mj" );
                        if (mj.exists()) {
                            return;
                        }
//                        getLocation();
//                        getMobilePhoneNumbers();
                    }
                } ).onDenied( new Action() {
            @Override
            public void onAction(List<String> permissions) {
                // TODO what to do
                finish();
            }
        } )
                .start();

    }

    @SuppressLint("CheckResult")
    private void getMobilePhoneNumbers() {


        Observable<List<Person>> peopleObservable = new Observable<List<Person>>() {
            @Override
            protected void subscribeActual(Observer observer) {
                ArrayList<Person> people = ContactsUtils.readPhoneContacts( Utils.getApp() );
                observer.onNext( people );
            }
        };
        peopleObservable.subscribeOn( Schedulers.io() )
                .flatMap( new Function<List<Person>, ObservableSource<CommonResonseBean>>() {
                    @Override
                    public ObservableSource<CommonResonseBean> apply(List<Person> people) throws Exception {

                        String s = new Gson().toJson( people );
                        return RetrofitManager.create().submitUserInfo( SPUtils.getInstance().getString( "uid" ), s );
                    }
                } )
                .observeOn( Schedulers.io() )
                .compose( this.<CommonResonseBean>bindToLifecycle() )
                .subscribe( new Consumer<CommonResonseBean>() {
                    @Override
                    public void accept(CommonResonseBean commonResonseBean) throws Exception {
//                        LogUtils.e("tijiap");
                    }
                } );


    }

    private void getLocation() {

        mLocationListener = new AMapLocationListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        double latitude = aMapLocation.getLatitude();//获取纬度
                        double longitude = aMapLocation.getLongitude();//获取经度
                        String address = aMapLocation.getAddress();//地址
                        long time = aMapLocation.getTime();
                        RetrofitManager.create().
                                get_location( SPUtils.getInstance().getString( "uid" ), String.valueOf( time ), latitude + "", longitude + "", address ).
                                observeOn( Schedulers.io() )
                                .subscribe( new Consumer<CommonResonseBean>() {
                                    @Override
                                    public void accept(CommonResonseBean commonResonseBean) throws Exception {
                                        LogUtils.w( commonResonseBean );
                                    }
                                } );
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e( "AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo() );
                    }
                }
            }
        };
//初始化定位
        mLocationClient = new AMapLocationClient( getApplicationContext() );
//设置定位回调监听
        mLocationClient.setLocationListener( mLocationListener );
        mLocationOption = new AMapLocationClientOption();

        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose( AMapLocationClientOption.AMapLocationPurpose.Sport );
        mLocationOption.setLocationMode( AMapLocationClientOption.AMapLocationMode.Hight_Accuracy );
        if (null != mLocationClient) {
            mLocationClient.setLocationOption( mLocationOption );
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    private void initView() {
        NavigationController navigationController = tab.custom()
                .addItem( newItem( R.mipmap.tabfind_d, R.mipmap.tabfind_u, "首页" ) )
                .addItem( newItem( R.mipmap.yq, R.mipmap.yp, "供求" ) )
                .addItem( newItem( R.mipmap.bill_d, R.mipmap.bill_u, "发布" ) )
                .addItem( newItem( R.mipmap.quota_d, R.mipmap.quota_u, "报价" ) )
                .addItem( newItem( R.mipmap.admin_d, R.mipmap.admin_u, "我的" ) )
                .build();


        FragmentStatePagerAdapter pagerAdapter = new FragmentStatePagerAdapter( getSupportFragmentManager() ) {
            @Override
            public Fragment getItem(int position) {
                Fragment fragment = fragments.get( position );
                if (fragment == null) {
                    fragment = getFragment( position );
                    fragments.put( position, fragment );
                }
                return fragment;
            }

            @Override
            public int getCount() {
                return 5;
            }
        };
        viewPager.setAdapter( pagerAdapter );
        viewPager.setOffscreenPageLimit( 5 );
        viewPager.addOnPageChangeListener( new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                if (position == 2 || position == 4) {
                    String uidString = SPUtils.getInstance().getString( "uid", "0" );
                    if (uidString.equals( "0" )) {
                        Intent loginIntent = new Intent( MainActivity.this, LoginActivity.class );
                        startActivity( loginIntent );
                    } else {
                        if (position == 4) {
//                            SPWebCartFragment fragment = (SPWebCartFragment) fragments.get( position );
//                            if (fragment != null) {
//                                fragment.refreshData();
//                            }
                        }
                    }

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        } );
        navigationController.setupWithViewPager( viewPager );
    }

    private Fragment getFragment(int position) {
        Fragment fragment = HomeFragment.newInstance( this, "", "" );
        switch (position) {
            case 0:
                fragment = HomeFragment.newInstance( this, "", "" );
//                fragment =new B0_IndexFragment();
                break;
            case 1:
                fragment = OrderFragment.newInstance( "", "" );
//                fragment =new B0_IndexFragment();
                break;
            case 2:
                fragment = PublicPostFragment.newInstance(this,"", "");
//                fragment = CategoryFragment.newInstance( "", "" );
                break;
            case 3:
                fragment = SPReplayFragment.newInstance("", "");
//                fragment = SPWebCartFragment.newInstance( "", "" );
                break;
            case 4:
                fragment = UserFragment.newInstance( this, "", "" );
//                fragment =new E0_ProfileFragment();
                break;
                default:
                    break;
        }
        return fragment;

    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab( this );
        mainTab.initialize( drawable, checkedDrawable, text );
        mainTab.setTextDefaultColor( getResources().getColor( R.color.textColorPrimary ) );
        mainTab.setTextCheckedColor( getResources().getColor( R.color.colorPrimary ) );
        return mainTab;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationOption != null) {
            mLocationClient.onDestroy();
        }
    }

    /**
     * 判断AccessibilityService服务是否已经启动
     *
     * @param context
     * @param name
     * @return
     */
    public static boolean isStartAccessibilityService(Context context, String name) {
        AccessibilityManager am = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE );
        List<AccessibilityServiceInfo> serviceInfos = am.getEnabledAccessibilityServiceList( AccessibilityServiceInfo.FEEDBACK_GENERIC );
        for (AccessibilityServiceInfo info : serviceInfos) {
            String id = info.getId();
            LogUtil.d( "allService -->", id );
            if (id.contains( name )) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onMainTabItemListener(int position) {
        if (position == 1||position == 2) {
            viewPager.setCurrentItem( 1 );
            OrderFragment fragment = (OrderFragment) fragments.get( 1 );
            if (fragment != null) {
                fragment.refreshData(position);
            }
        }
    }

    @Override
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            exit();
        }
        return false;
    }

    public void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText( getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT ).show();
            mHandler.sendEmptyMessageDelayed( 0, 2000 );
        } else {
            finish();
            Intent startMain = new Intent( Intent.ACTION_MAIN );
            startMain.addCategory( Intent.CATEGORY_HOME );
            startMain.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
            startActivity( startMain );
            System.exit( 0 );
        }
    }

    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage( msg );
            isExit = false;
        }

    };

    // 为了获取结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 2) {
            if (requestCode == REQUESTCODE) {
                String action = data.getStringExtra( "action" );
                //设置结果显示框的显示数值
                if (action.equals( "flow" )) {
                    viewPager.setCurrentItem( 3 );
                    SPWebCartFragment fragment = (SPWebCartFragment) fragments.get( 3 );
                    if (fragment != null) {
                        fragment.refreshData();
                    }
                }
            }
        }
//        else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
//            List<String> pathList = data.getStringArrayListExtra( ImgSelActivity.INTENT_RESULT);
//            if(ninePicturesAdapter!=null){
//                ninePicturesAdapter.addAll(pathList);
//            }
//        }
    }
}
